package com.wu.foodsafetyplayer.app.fragment.viewpager;

import android.content.Intent;
import android.graphics.drawable.StateListDrawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.wu.foodsafetyplayer.R;
import com.wu.foodsafetyplayer.app.AppVideoActivity;
import com.wu.foodsafetyplayer.app.LoginActivity;
import com.wu.foodsafetyplayer.app.adapter.MonitorVideoAdapter;
import com.wu.foodsafetyplayer.app.adapter.VideoNvaAdapter;
import com.wu.foodsafetyplayer.app.bean.MonitorVideoBean;
import com.wu.foodsafetyplayer.app.dialog.DevicePopWindow;
import com.wu.foodsafetyplayer.app.dialog.LoadingUtil;
import com.wu.foodsafetyplayer.app.fragment.BaseFragment;
import com.wu.foodsafetyplayer.http.CommonOkHttpClient;
import com.wu.foodsafetyplayer.utils.ACache;
import com.wu.foodsafetyplayer.utils.AnimationUtil;
import com.wu.foodsafetyplayer.utils.PopupUtil;
import com.wu.foodsafetyplayer.utils.SpUtil;
import com.wu.foodsafetyplayer.widget.MyGridView;

import java.io.IOException;

import androidx.annotation.NonNull;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class MyHouseFragment extends BaseFragment implements View.OnClickListener, AdapterView.OnItemClickListener {
    private static final String TAG = MyHouseFragment.class.getSimpleName();
    private GridView videoGridView;
    private MyGridView videoNvaGridView;
    private MonitorVideoBean monitorVideoBean;
    private String res;//设备数据

    private DevicePopWindow devicePopWindow;
    private ImageView f_nonitor_add;
    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_monitor;
    }

    @Override
    protected void initView() {
        super.initView();
        f_nonitor_add = findViewById(R.id.f_nonitor_add);
        f_nonitor_add.setOnClickListener(this);
        //设备分类
        videoNvaGridView = findViewById(R.id.f_monitor_video_nva_gv);
        videoNvaGridView.setSelector(new StateListDrawable());//不要选中时的背景效果
        videoNvaGridView.setOnItemClickListener(this);
        VideoNvaAdapter videoNvaAdapter = new VideoNvaAdapter(getActivity());
        videoNvaGridView.setAdapter(videoNvaAdapter);
        //监控设备
        videoGridView = findViewById(R.id.f_monitor_video_gv);
        videoGridView.setOnItemClickListener(this);
        res = ACache.get(getActivity()).getAsString("live_data");
        if (!TextUtils.isEmpty(res)) {
            try {
                monitorVideoBean = new Gson().fromJson("{\"data\": " + res + "}", MonitorVideoBean.class);
                if (monitorVideoBean != null && monitorVideoBean.data != null && !monitorVideoBean.data.isEmpty()) {
                    handler.sendEmptyMessage(0);
                }
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
            }
        }
        initData();
    }

    /**
     * 初始化数据
     */
    public void initData() {
        devicePopWindow = new DevicePopWindow(getActivity());
        devicePopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                PopupUtil.INSTANCE.backgroundAlpha(getActivity(),1f);
            }
        });
        LoadingUtil.INSTANCE.showLoading(getActivity(),"加载中");
        CommonOkHttpClient.FUNC_TASK.execute(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient().newBuilder()
                        .build();
                Request request = new Request.Builder()
                        .url("http://daxun.tpddns.cn:81/live/Query?username=admin&password=admin&treemode=0&name=")
                        .method("GET", null)
                        .addHeader("content-type", "form-data")
                        .addHeader("Cookie", "IDHTTPSESSIONID=r4EN2qalGkkbZUS")
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    String res2 = response.body().string();
                    Log.e(TAG, "-----initData: " + res);
                    if (!TextUtils.isEmpty(res2)) {
                        LoadingUtil.INSTANCE.dismissLoading(getActivity());
                        if (res2.equals(res)) {
                            return;
                        }
                        ACache.get(getActivity()).put("live_data", res2);
                        monitorVideoBean = new Gson().fromJson("{\"data\": " + res2 + "}", MonitorVideoBean.class);
                        if (monitorVideoBean != null && monitorVideoBean.data != null && !monitorVideoBean.data.isEmpty()) {
                            handler.sendEmptyMessage(0);
                        }
                    }
                } catch (IOException e) {
                    LoadingUtil.INSTANCE.dismissLoading(getActivity());
                    e.printStackTrace();
                } catch (ClassCastException e) {
                    LoadingUtil.INSTANCE.dismissLoading(getActivity());
                    Log.e(TAG, "开始请求设备数据成功,解析失败");
                } catch (JsonSyntaxException e) {
                    LoadingUtil.INSTANCE.dismissLoading(getActivity());
                    e.printStackTrace();
                }finally {
                    //不管请求结果怎么样，都关闭弹窗
                    LoadingUtil.INSTANCE.dismissLoading(getActivity());
                }
            }
        });
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            MonitorVideoAdapter videoAdapter = new MonitorVideoAdapter(getActivity(), monitorVideoBean);
            videoGridView.setAdapter(videoAdapter);
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //添加摄像头
            case R.id.f_nonitor_add:
                if (!SpUtil.INSTANCE.getUserInfo().getIsnoLogin()){
                    devicePopWindow.showAsDropDown(f_nonitor_add,-150,10);
                    PopupUtil.INSTANCE.backgroundAlpha(getActivity(),0.8f);
                }else {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                }
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        switch (adapterView.getId()) {
            case R.id.f_monitor_video_nva_gv:
                videoNvaGridView.setCurrentPosition(i);
                AnimationUtil.setScaleAnimation(getActivity(), view);
                if (i > 0) {
                    Toast.makeText(getActivity(), "该分组暂无设备", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.f_monitor_video_gv:
                Intent intent = new Intent(getActivity(), AppVideoActivity.class);
                intent.putExtra("name", monitorVideoBean.data.get(i).name);
                intent.putExtra("url", monitorVideoBean.data.get(i).url);
                startActivity(intent);
                break;
        }
    }


}
